#Module that combines the Python Imaging Library with gtk screen capture.
#Version 1 will perform the process linearly. (No pipelining)
#Later versions will include multiprocessing to help speed up the image capture process.

import gtk.gdk
import time
from PIL import Image
from PIL import ImageChops
from PIL import ImageEnhance
from PIL import ImageDraw
from PIL import ImageFilter

w = gtk.gdk.get_default_root_window()
sz = w.get_size()
w_mod = 3
h_mod = 2
color = (255, 0, 0)
image_size = (300,300)
red =Image.new("RGB", image_size, color)
print "The size of the window is %d x %d" % sz
i = 0
while(1):
	start_time = time.time()
	pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,image_size[0],image_size[1])
	pb = pb.get_from_drawable(w,w.get_colormap(),60,80,0,0,image_size[0],image_size[1])
	if (pb != None):
		#Now do image processing from the pixel buffer
		im = Image.frombuffer("RGB", (image_size[0],image_size[1]), pb.get_pixels(), 'raw', "RGB", 0, 1)
		#im.show()
		out = ImageChops.difference(red, im)
		out = out.convert("L") #Convert to grey scale.
		result = Image.eval(out, lambda x: 255 if x < 70 else 0) #Get the colored image
		filtered = result.filter(ImageFilter.MinFilter(9))
		#Finally, we calculate display the bounding box.
		bbox = filtered.getbbox()
		#Finally, find the hotspot of the image
		#First figure out if bbox exists
		if bbox:
			box_w = (bbox[0] + bbox[2])/2
			box_h = (bbox[1] + bbox[3])/2
			hotspot = (box_w, box_h)
			area_x = abs(bbox[0] - bbox[2])
			area_y = abs(bbox[1] - bbox[3])
			Area = area_x*area_y
			print "Bounding box: " + str(bbox) + " Hotspot: " + str(hotspot) + "Area: " + str(Area)
	else:
    		print "Unable to get the screenshot."
	end_time = time.time()
	print "Time used: " + str(end_time - start_time)

